import React, { useEffect, useRef, useState } from 'react'
import style from "./upload.module.css";
import { Popover, Input, Tabs, Button, Upload, message } from 'antd';
import { SearchOutlined, SettingOutlined, DeleteOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import ImgCrop from 'antd-img-crop';



function Index() {
  //tab切换的key值
  const [key, setkey] = useState('0')
  //imglist
  const [fileList, setFileList] = useState(localStorage.getItem('fileList') ? JSON.parse(localStorage.getItem('fileList') as string) : [])
  //上传图片事件
  const handleChange = (info: any) => {
    console.log(info);
    const updatedFileList = info.fileList.map((item: any) => {
      if (item.type === 'video/mp4') {
        const isValidSize = item.size <= 100 * 1024 * 1024; // 100MB
        const estimatedDuration = getEstimatedDuration(item.size)
        if (!isValidSize || Number(estimatedDuration) > 180) { // 3分钟
          message.error(`${item.name} 文件不符合要求：最大100MB和3分钟`);
          return Upload.LIST_IGNORE;
        }
      }
      else if (item.type === 'audio/mpeg') {
        const isValidSize = item.size <= 20 * 1024 * 1024; // 20MB
        const estimatedDuration = getEstimatedDuration(item.size);

        if (!isValidSize || Number(estimatedDuration) > 300) { // 5分钟
          message.error(`${item.name} 文件不符合要求：最大20MB和5分钟`);
          return Upload.LIST_IGNORE;
        }
      }

      return {
        ...item,
        url: `http://localhost:3000/${item.name}`, // 假设这里的 URL 是有效的,
      };
    });

    setFileList(updatedFileList); // 更新状态

    // 将更新后的 fileList 存储到 localStorage
    localStorage.setItem('fileList', JSON.stringify(updatedFileList));

  }
  //粗略计算时常
  const getEstimatedDuration = (size: number) => {
    //音频文件的大小，以字节为单位（例如，2 MB = 2 * 1024 * 1024 字节）
    //出音频的总时长（秒）   * 60 =  1 分钟 = 60 秒  计算出分钟
    return (size / (128 * 1024)) * 60; // 假设128kbps的音频
  };
  // useEffect(() => {
  //   localStorage.setItem('fileList', JSON.stringify(fileList));
  // }, [fileList])
  //上传图片
  const props: UploadProps = {
    beforeUpload: (file) => {
      console.log(file);

      const isPNG = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg' || file.type === 'video/mp4' || file.type === 'audio/mpeg';
      if (!isPNG) {
        message.error(`${file.name} 不是png或者jpeg或者svg,mp4,mp3的格式`);
        return isPNG || Upload.LIST_IGNORE;
      }
      if (file.size / 1024 / 1024 > 20) { // 20MB
        message.error(`${file.name} 文件大小不能超过 20MB`);
        return isPNG || Upload.LIST_IGNORE;
      }
    },
    onChange: handleChange,
    fileList
  };
  //上传视频
  const rendervideo = () => {
    const vid0pFiles = fileList.filter((item: any) => item.type == 'video/mp4')
    return <div>
      {
        vid0pFiles.map((file: any) => {
          return <div className={style.picture} key={file.uid}>
            <video width={200} height='auto' controls>
              <source src={`../../../../server/public/${file.name}`} type={file.type} />
            </video>
            {
              bool1 ? <input type="checkbox" className={style.inpbox}
                checked={selectedvideo.includes(file.name)}
                onChange={() => dx1(file.name)}
              /> : ''
            }
          </div>
        })
      }
    </div>
  }
  //上传音频
  const renderaudio = () => {
    const audilFiles = fileList.filter((item: any) => item.type == 'audio/mpeg')
    return audilFiles.length > 0 ?
      (
        <div>
          {
            audilFiles.map((file: any) => {
              return <div style={{ position: "relative" }}>
                <audio key={file.uid} controls style={{ width: '250px' }}>
                  <source src={file.url} type={file.type} />
                </audio>
                {
                  bool2 ? <input type="checkbox"
                    checked={selectedaudio.includes(file.name)}
                    onChange={() => dxaudio(file.name)}
                    style={{ position: 'absolute', right: '5px', top: '20px' }} />
                    : ""
                }
              </div>
            })
          }
        </div>
      )
      : ''
  }
  //tab切换事件
  const onChange = (key: string) => {
    console.log(key);
    setkey(key)
  };
  const items: any = [
    {
      key: '0',
      label: '图片',
      contant: 'Content of Tab Pane 1',
    },
    {
      key: '1',
      label: '视频',
      contant: 'Content of Tab Pane 2',
    },
    {
      key: '2',
      label: '音频',
      contant: 'Content of Tab Pane 3',
    },
  ];
  //上传内容限制
  const content = (
    <div style={{ background: '#1b2337', color: '#fff' }}>
      <p>上传格式支持：</p>
      <p>图片：20MB png、jpeg、svg格式</p>
      <p>动图：5MB以内,gif格式</p>
      <p>视频：100MB、3分钟以内,mp4格式</p>
      <p>音频：20MB、5分钟以内,mp3格式</p>
    </div>
  );
  //设置多选
  const [selectedFiles, setSelectedFiles] = useState([])
  const [selectedvideo, setSelectedvideo] = useState([])
  const [selectedaudio, setSelectedaudio] = useState([])
  const [bool, setBool] = useState(false)
  const [bool1, setBool1] = useState(false)
  const [bool2, setBool2] = useState(false)
  //设置按钮
  const alldx = () => {
    setBool(!bool)
  }
  const [isAllSelected, setIsAllSelected] = useState(false);

  useEffect(() => {
    const allFiles = fileList.filter(file =>
      file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg'
    );
    setIsAllSelected(allFiles.length > 0 && allFiles.every(file => selectedFiles.includes(file.name)));
  }, [selectedFiles, fileList]);
  //全选
  const handleSelectAll = (e: any) => {
    const ischecked = e.target.checked;
    const allFiles = fileList.filter((file: any) =>
      file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg'
    );
    const updateallFiles = allFiles.map((file: any) => file.name)
    setSelectedFiles(ischecked ? updateallFiles : [])
  }
  //单选
  console.log(selectedFiles);
  const dx = (fileName: any) => {
    console.log(fileName);

    if (selectedFiles.includes(fileName)) {
      //如果存在就移出
      const newfiles = selectedFiles.filter(item => item !== fileName)
      setSelectedFiles(newfiles)
      console.log(selectedFiles, 1111);
    }
    else {
      const newfiles = [...selectedFiles, fileName]
      setSelectedFiles(newfiles)
      console.log(selectedFiles, 222);
    }
  }
  //删除
  const delall = () => {
    message.success('删除成功')
    const updatedFileList = fileList.filter(file => !selectedFiles.includes(file.name));
    setFileList(updatedFileList);
    localStorage.setItem('fileList', JSON.stringify(updatedFileList)); // 重新存储
    setSelectedFiles([]); // 清空选中状态
  }


  //视频
  const alldx1 = () => {
    setBool1(!bool1)
  }
  const [isAllSelected1, setIsAllSelected1] = useState(false);

  useEffect(() => {
    const allFiles = fileList.filter(file =>
      file.type === 'video/mp4'
    );
    setIsAllSelected1(allFiles.length > 0 && allFiles.every(file => selectedvideo.includes(file.name)));
  }, [selectedvideo, fileList]);
  console.log(selectedvideo);
  // 全选
  const handleSelectAll1 = (e: any) => {
    const isChecked = e.target.checked;
    const allFiles = fileList.filter(file => file.type === 'video/mp4');
    const updateAllFiles = allFiles.map(file => file.name);

    setSelectedvideo(isChecked ? updateAllFiles : []); // 根据全选状态更新
  };

  // 单选
  const dx1 = (fileName: any) => {
    if (selectedvideo.includes(fileName)) {
      const newFiles = selectedvideo.filter(item => item !== fileName); // 移除已选择的文件
      setSelectedvideo(newFiles);
    } else {
      const newFiles = [...selectedvideo, fileName]; // 添加新选择的文件
      setSelectedvideo(newFiles);
    }
  };
  //删除
  const delall1 = () => {
    message.success('删除成功')
    const updatedFileList = fileList.filter(file => !selectedvideo.includes(file.name));
    setFileList(updatedFileList);
    localStorage.setItem('fileList', JSON.stringify(updatedFileList)); // 重新存储
    setSelectedvideo([]); // 清空选中状态
  }



  //音频
  const alldx2 = () => {
    setBool2(!bool2)
  }
  const [isAllSelected2, setIsAllSelected2] = useState(false);
  useEffect(() => {
    const allFiles = fileList.filter(file =>
      file.type === 'audio/mpeg'
    );
    setIsAllSelected2(allFiles.length > 0 && allFiles.every(file => selectedaudio.includes(file.name)));
  }, [selectedaudio, fileList]);
  // console.log(selectedaudio);
  // 全选
  const handleSelectAllaudio = (e: any) => {
    const isChecked = e.target.checked;
    const allFiles = fileList.filter(file => file.type === 'audio/mpeg');
    const updateAllFiles = allFiles.map(file => file.name);

    setSelectedaudio(isChecked ? updateAllFiles : []); // 根据全选状态更新
  };

  // 单选
  const dxaudio = (fileName: any) => {
    if (selectedaudio.includes(fileName)) {
      const newFiles = selectedaudio.filter(item => item !== fileName); // 移除已选择的文件
      setSelectedaudio(newFiles);
    } else {
      const newFiles = [...selectedaudio, fileName]; // 添加新选择的文件
      setSelectedaudio(newFiles);
    }
  };
  // //删除
  const delaudio = () => {
    message.success('删除成功')
    const updatedFileList = fileList.filter(file => !selectedaudio.includes(file.name));
    setFileList(updatedFileList);
    localStorage.setItem('fileList', JSON.stringify(updatedFileList)); // 重新存储
    setSelectedaudio([]); // selectedaudio清空选中状态
  }
  return (
    <div className={style.main}>
      <div className={style.top}>
        <h3>
          我的上传
        </h3>
        <Popover content={content}>
          {/* <ImgCrop rotationSlider> */}
            <Upload
              {...props}
              fileList={fileList}
              action="http://localhost:3000/api/ben"
              showUploadList={false}
              onChange={handleChange}
            // onPreview={onPreview}
            >
              <Button type="primary">上传素材</Button>
            </Upload>
          {/* </ImgCrop> */}
        </Popover>
      </div>
      <div style={{ display: 'flex', justifyContent: 'center', height: '50px' }}>
        <Input placeholder="搜索素材" prefix={<SearchOutlined />} className={style.inp} />
      </div>
      {/* tab切换 */}
      <div style={{ marginLeft: '10px', marginRight: '10px' }}>
        <Tabs defaultActiveKey="0" onChange={onChange} >
          {
            items.map((item: any, index: number) => {
              return <Tabs.TabPane tab={item.label} key={index}>
              </Tabs.TabPane>
            })
          }
        </Tabs>
      </div>
      {/* tab切换内容 */}
      <div className={style.tabmain}>
        <div>
          {/* {
            items.map((item: any, index: any) => {
              return <div key={index}
                style={{ display: key == index ? 'block' : 'none' }}
              >
                {item.contant}
              </div>
            })
          } */}
          {
            key == '0' ?
              <div>
                <div className={style.tabcontainer}>
                  <div className={style.tabtop}>
                    <h3>资源</h3>
                    <p>
                      {fileList.filter((file: any) => file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg').length}
                    </p>
                  </div>
                  <SettingOutlined style={{ fontSize: '16px' }} onClick={alldx} />
                </div>
                {
                  bool ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div><input type="checkbox" name="" id=""
                      checked={isAllSelected}
                      onChange={handleSelectAll}
                    />已经选择{selectedFiles.length}</div>
                    <div>
                      <DeleteOutlined onClick={delall} />
                      <span style={{ marginLeft: '10px' }} onClick={() => setBool(false)}>取消</span></div>
                  </div> : ''
                }
                <div className={style.imgall}>
                  {
                    fileList.filter((file: any) => file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/svg')
                      .map((file, index: number) => (
                        <div key={index} draggable>
                          {file.originFileObj && (
                            <div className={style.picture}>
                              <img
                                src={`../../../../server/public/${file.name}`} // 使用 Blob URL
                                alt={file.name}
                              />
                              {
                                bool ? <input type="checkbox" className={style.inpbox}
                                  checked={selectedFiles.includes(file.name)}
                                  onChange={() => dx(file.name)}
                                /> : ''
                              }
                            </div>
                          )}
                        </div>
                      ))
                  }
                </div>
              </div>
              : ''
          }
          {/* 视频 */}
          {
            key == '1' ?
              <div>
                <div className={style.tabcontainer}>
                  <div className={style.tabtop}>
                    <h3>资源</h3>
                    <p>
                      {fileList.filter((item: any) => item.type == 'video/mp4').length}</p>
                  </div>
                  <SettingOutlined style={{ fontSize: '16px' }} onClick={alldx1} />
                </div>
                {
                  bool1 ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>全选视频：<input type="checkbox" name="" id=""
                      checked={isAllSelected1}
                      onChange={handleSelectAll1}
                    />已经选择{selectedvideo.length}</div>
                    <div><DeleteOutlined onClick={delall1} /><span style={{ marginLeft: '10px' }} onClick={() => setBool1(false)}>取消</span></div>
                  </div> : ''
                }
                <div>
                  {rendervideo()}
                </div>
              </div>
              : ''
          }
          {/* 音频 */}
          {
            key == '2' ?
              <div>
                <div className={style.tabcontainer}>
                  <div className={style.tabtop}>
                    <h3>资源</h3>
                    <p>
                      {fileList.filter((item: any) => item.type == 'audio/mpeg').length}</p>
                  </div>
                  <SettingOutlined style={{ fontSize: '16px' }} onClick={alldx2} />
                </div>
                {
                  bool2 ? <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <div>全选<input type="checkbox" name="" id=""
                      checked={isAllSelected2}
                      onChange={handleSelectAllaudio}
                    />已经选择{selectedaudio.length}</div>
                    <div><DeleteOutlined onClick={delaudio} /><span style={{ marginLeft: '10px' }} onClick={() => setBool2(false)}>取消</span></div>
                  </div> : ''
                }
                <div>
                  {renderaudio()}
                </div>
              </div>
              : ''
          }
        </div>
      </div>
    </div>
  )
}

export default Index
